<?php

namespace App\Service\CallingCards;

use App\Models\Common\ConfigModel;
use App\Models\FeishuCallingCard\FeishuCallingCardInvestmentEmployeeModel;
use App\Models\Kms\User\KmsUser;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class XiaokeService
{
    /**
     * 通过飞书一级部门名称或者真实姓名获取线索所属人 ID
     */
    public static function getOwerByDepartmentName($departmentName, $name, $area = [])
    {
        // 特殊用户
        $realName = self::getRealName($name);
        // 判断是否是自有线索
        $staff = FeishuCallingCardInvestmentEmployeeModel::allStaff();
        $v = collect($staff)
            ->where('name', $realName)
            ->where('direct', 1)
            ->first();
        if (null !== $v) {
            return $v['xiaokeUserId'];
        }

        $userListFile = resource_path('feishuCallingCards/xiaokeUsers.json');
        $userList = json_decode(file_get_contents($userListFile), true);
        // 特殊部门
        if (isset($userList['department'][$departmentName])) {
            return $userList['department'][$departmentName];
        }

        // 分公司员工-分配给灵文(省区拉新)
        // 其他内部员工推荐-分配给灵文(内部推荐)
        if ($departmentName) {
            $rootDepartmentName = KmsUser::query()
                ->where("rootDepartmentName", "<>", "")
                ->where("isExited", 0)//是否已离职
                ->where("resignedTime", 0)//离职时间
                ->groupBy('rootDepartmentName')
                ->pluck('rootDepartmentName')
                ->toArray();
            if (in_array($departmentName, $rootDepartmentName)) {
                return ConfigModel::getXiaokeConfig();//来源为省区拉新及内部推荐的线索分配至商增客服灵文销氪名下,销氪ID：2974500871
            }
        }

        // 重点城市线索 分配给城市专属招商

        $match = function ($string, $keyword) {
            $pattern = '/(' . implode('|', $keyword) . ')/';
            return (bool)preg_match($pattern, $string);
        };

        $province = $area['province'] ?? '';
        $city     = $area['city'] ?? '';
        if ($match($province, ['北京', '上海', '天津', '重庆', '台湾'])) {
            $city = $province;
        }
        if ($city) {
            $xiaokeUserIds = [];
            FeishuCallingCardInvestmentEmployeeModel::query()
                ->chunkById(
                    100, function ($item) use ($match, $city, &$xiaokeUserIds) {
                    foreach ($item as $v) {
                        $cityCodes = $v->cityCodes ? json_decode($v->cityCodes, true) : [];
                        if ($v->city && $cityCodes && $v->xiaokeUserId) {
                            foreach ($cityCodes as $area) {
                                if (isset($area['provinceName']) && $area['provinceName'] == '台湾') {
                                    $area['cityName'] = $area['provinceName'];
                                }
                                if ($match($city, [$area['cityName']])) {
                                    $xiaokeUserIds[] = $v->xiaokeUserId;
                                    break;
                                }
                            }
                        }
                    }
                }
                );

            if ($xiaokeUserIds) {
                $xiaokeUserIds = array_unique($xiaokeUserIds);
                $cacheKey      = "xiaoke_last_userId:" . $city;          //上一个自动分配的销售经理
                $lastUserId    = (int)Cache::get($cacheKey);
                $userId        = self::getUserIdByLastUser($xiaokeUserIds, $lastUserId);
                Cache::put($cacheKey, $userId);
                return $userId;
            }
        }

        // 招商均分公海--原逻辑


        $cacheKey   = "xiaoke_last_userId";          //上一个自动分配的销售经理
        $lastUserId  = (int)Cache::get($cacheKey);
        $kuafuXiaokeUserIds = collect($staff)
            ->where('public', 1)
            ->pluck('xiaokeUserId')
            ->toArray();
        $userId = self::getUserIdByLastUser($kuafuXiaokeUserIds, $lastUserId);
        Cache::put($cacheKey, $userId);
        return $userId;
    }

    /**
     * 按顺序获取招商经理销氪用户 ID
     */
    public static function getUserIdByLastUser($userList, int $lastUserId)
    {
        if ($lastUserId) {
            $flag = false;
            foreach ($userList as $item) {
                if ($flag) {
                    return $item;
                }

                if ($item == $lastUserId) {
                    $flag = true;
                }
            }
        }

        return array_shift($userList);
    }

    /**
     * 通过花名获取真实姓名
     */
    public static function getRealName($name)
    {
        $endNum = strpos($name, '（');
        if ($endNum === false) {
            $endNum = strpos($name, '(');
        }

        return $endNum > 0 ? substr($name, 0, $endNum) : $name;
    }

    /**
     * 传入部门名称 字符串，返回 线索来源  字符串，其他情况 返回 内部推荐
     * @param string $department
     * @param string $name 销售姓名
     * @return string
     */
    public static function getSourceByDepartment(string $department, string $name = ""): string
    {
        // 指定的用户
        $realName = self::getRealName($name);
        $allStaff = FeishuCallingCardInvestmentEmployeeModel::allStaff();
        foreach ($allStaff as $v) {
            if ($v['name'] == $realName && strlen(trim($v['source']))) {
                return $v['source'];
            }
        }

        if ('盛世代招' == $department) {
            return '盛世代招';
        }

        if (Str::endsWith($department, '分公司')) {
            return '省区拉新';
        }

        return '内部推荐';
    }
}
